package 算法部分.两数之和;

import java.util.HashMap;

/**
 * 给定 nums = [2, 7, 11, 15], target = 9
 * <p>
 * 因为 nums[0] + nums[1] = 2 + 7 = 9
 * 所以返回 [0, 1]
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/two-sum
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @Author idea
 * @Date created in 7:34 下午 2020/4/17
 */
public class Demo {

    /**
     * 数组中的元素不会重复
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> temp = new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if (temp.containsKey(diff)) {
                return new int[]{temp.get(diff), i};
            }
            temp.put(nums[i], i);
        }
        throw new RuntimeException("no two sum solution!");
    }

    public static void main(String[] args) {
        Demo d = new Demo();
        int[] result = d.twoSum(new int[]{3, 2, 31, 4}, 3);
        for (int i : result) {
            System.out.println(i);
        }
    }
}
